// <GUI menuname="Report Parameters and PDF" tooltip="Report Parameters and PDF"/>

/******************************************************************************************************
Copyright (C) 2009 Mestrelab Research S.L. All rights reserved.

This file is part of the MNova scripting toolkit.

Authorized users of MNova Software may use this file freely, but this file is provided AS IS
with NO WARRANTY OF ANY KIND, INCLUDING THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE.
*****************************************************************************************************/

function reportParametersAndPDF()
{
	if( reportParametersAndLayout(true) ) //set parameter to false not to add the spectrum title
		mainWindow.doAction("action_File_ExportToPDF");
}

function getTitleString(aSpectrum)
{
	var titleString = "<b>%1</b>";
	var spectrumTitle = aSpectrum.getParam("Title");
	var splitTitle = spectrumTitle.split("\n");//we only want the first line of the title
	var removeRegExp = new RegExp(";$");//removes ";" at the end of the title
	return titleString.replace("%1", splitTitle[0].replace(removeRegExp,""));
}

function reportParametersAndLayout(addTitle)
{
	var dw = new DocumentWindow(mainWindow.activeWindow());
	var cP = new Page(dw.curPage());
//Select the first NMR Spectrum
	var spcItem = cP.item(0, "NMR Spectrum");
	if(!spcItem.isValid())
		return false;
	dw.setSelection(spcItem);
//Is there a previous report?
	var reportItem = undefined;
	var textItem = undefined;
	var rExp = new RegExp('^Parameters,.*');
	for( var i = 0; i<cP.itemCount("Text"); i++ )
	{
		textItem = cP.item(i,"Text");
		if(textItem.type == "NMR Table" && rExp.test(textItem.subtype) )
		{
			hasReport =true;
			reportItem = textItem;
		}
	}
//If not, create one
	if( reportItem == undefined )
	{
		mainWindow.doAction("NMRParametersTable::action_Report");
		reportItem = cP.item(0, "Text");
	}
//Layout the new list of items
	var titleItem = undefined;
	if( addTitle == true )
	{
		//Get title
		var titleString = getTitleString(nmr.activeSpectrum());
		titleItem = draw.text(titleString, true);
		titleItem.left = (cP.left+cP.right-titleItem.width)/2.0;
	}
	spcItem.width = 2.0*cP.width/3.0;
	if( titleItem == undefined )
		spcItem.top = cP.top;
	else
		spcItem.top = titleItem.bottom;
	spcItem.bottom = cP.bottom;
	reportItem.left = spcItem.right;
	reportItem.top = spcItem.top;
	reportItem.width = cP.width/3.0;
	reportItem.bottom = cP.bottom;

	spcItem.update();
	reportItem.update();
	dw.update();
	return true;
}
